<template>
  <div class="container">
    <!-- 搜索条件 -->
    <el-form
      class="filters"
      ref="searchForm"
      :model="searchForm"
      label-width="90px"
    >
      <el-row style="width: 100%">
        <el-col :span="6">
          <el-form-item label="设备编码" style="width: 100%">
            <el-input
              type="textarea"
              :rows="5"
              :placeholder="'请输入柜号，多个编码之间请回车换行，禁止输入特殊字符！最多输入100个设备号！输入示例：CC08DPC0202204250001\nCC08DPC0202205070001\n0000092011500063'"
              v-model="searchForm.codes"
              @change.native="keyUp($event)"
              @input.native="keyInput($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="18" class="filters">
          <el-form-item label="主控版本">
            <el-input
              v-model="searchForm.masterVersion"
              placeholder="请输入主控版本"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="仓控版本">
            <el-input
              v-model="searchForm.binVersion"
              placeholder="请输入仓控版本"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="柜控版本">
            <el-input
              v-model="searchForm.cabinetVersion"
              placeholder="请输入柜控版本"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="运营商">
            <el-input
              v-model="searchForm.operatorName"
              placeholder="请输入运营商名称"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否在线">
            <el-select
              style="width: 184px"
              v-model="searchForm.isOnline"
              placeholder="请选择是否在线"
              size="small"
            >
              <el-option
                v-for="item in enums.IS_ONLINE"
                :key="item.code"
                :label="item.label"
                :value="item.code"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签" v-if="tagList.length > 0" class="tag-item">
            <el-tooltip
              v-if="tagList.length > 0"
              :content="
                searchForm.isContain == 0 ? '包含选中标签' : '不包含选中标签'
              "
              placement="top"
            >
              <el-checkbox
                class="isContain"
                size="mini"
                :label="
                  searchForm.isContain == 0 ? '包含选中标签' : '不含选中标签'
                "
                border
                @change="tagCheckChange"
              ></el-checkbox>
            </el-tooltip>
            <el-checkbox-group v-model="searchForm.tagIds">
              <el-checkbox
                size="small"
                class="tag-radio"
                :label="item.id"
                v-for="(item, index) in tagList"
                :key="index"
                >{{ item.name }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>

          <div class="search-btns">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-search"
              @click="doSearch"
              >搜索</el-button
            >
            <el-button
              type="default"
              size="mini"
              icon="el-icon-refresh"
              @click="clearSearch"
              >重置</el-button
            >
          </div>
        </el-col>
      </el-row>
    </el-form>

    <div class="titles">
      <h3>{{ equipType == "CHARGING_CABINET" ? "充电柜" : "换电柜" }}</h3>
      <div class="btn_right">
        <span v-show="selectData.length > 0"
          >当前选择 {{ selectData.length }} 条数据</span
        >
        <el-button
          type="success"
          size="medium"
          :disabled="selectData.length == 0"
          @click="batchSetTags"
          >批量设置标签</el-button
        >
        <el-button
          type="success"
          size="medium"
          :disabled="selectData.length == 0"
          @click="batchSearch"
          >批量查询版本</el-button
        >
        <el-button
          type="primary"
          size="medium"
          :disabled="selectData.length == 0"
          @click="batchUpdate"
          >批量升级(选中)</el-button
        >
        <el-button
          type="primary"
          size="medium"
          :disabled="tableData.length == 0"
          @click="conditionUpdate"
          >批量升级(条件)</el-button
        >
        <el-button type="primary" size="medium" @click="batchAdd"
          >批量新增</el-button
        >
        <!-- <el-button type="primary" size="medium" @click="batchAddUpdate"
          >导入并升级</el-button
        > -->
      </div>
    </div>

    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      v-loading="listLoading"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      :cell-style="centerStyle"
      :header-cell-style="centerStyle"
    >
      <el-table-column type="selection"> </el-table-column>
      <el-table-column
        prop="code"
        label="编码"
        min-width="200"
      ></el-table-column>
      <el-table-column prop="masterVersion" label="主控" min-width="110">
      </el-table-column>
      <el-table-column
        prop="binVersion"
        label="仓控"
        min-width="200"
      ></el-table-column>
      <el-table-column
        prop="cabinetVersion"
        label="柜控"
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="powerSupplyVersion"
        label="电源版本"
        min-width="120"
      ></el-table-column>
      <el-table-column prop="isOnline" label="是否在线" min-width="78">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.isOnline == 1">在线</el-tag>
          <el-tag type="danger" v-else-if="scope.row.isOnline == 0"
            >离线</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="alarmSemaphoreName"
        label="最近告警"
        min-width="120px"
      ></el-table-column>
      <el-table-column
        prop="occurrenceTime"
        label="告警时间"
        min-width="160px"
      ></el-table-column>

      <el-table-column
        prop="lastOnlineTime"
        label="最近上线时间"
        min-width="160"
      ></el-table-column>
      <el-table-column
        prop="lastOfflineTime"
        label="最近离线时间"
        min-width="160"
      ></el-table-column>

      <el-table-column prop="remark" label="备注" min-width="160px">
        <template slot-scope="scope">
          <span class="word-wrap" v-html="scope.row.remark"></span>
          <i class="el-icon-edit" @click="isRemarkRow(scope.row)"></i>
        </template>
      </el-table-column>
      <el-table-column prop="tagsName" label="标签" width="120">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.tagsName" placement="top">
            <span class="tagsName">{{ scope.row.tagsName }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="功能" fixed="right" min-width="120">
        <template slot-scope="scope">
          <el-popover placement="left" width="50" trigger="click">
            <el-button
              @click.native.prevent="logRow(scope.row, 1)"
              class="borbot"
              plain
              size="small"
            >
              连接
            </el-button>
            <el-button
              @click.native.prevent="logRow(scope.row, 2)"
              plain
              size="small"
            >
              告警
            </el-button>
            <el-button type="text" size="small" slot="reference" class="log_btn"
              >日志<i class="el-icon-d-arrow-right el-icon--right"></i
            ></el-button>
          </el-popover>
          <el-popover placement="left" width="50" trigger="click">
            <el-button
              @click.native.prevent="handleRow(scope.row, 1)"
              class="borbot"
              type="primary"
              plain
              size="small"
            >
              升级
            </el-button>
            <el-button
              @click.native.prevent="handleRow(scope.row, 2)"
              class="borbot"
              type="primary"
              plain
              size="small"
            >
              提取日志
            </el-button>
            <el-button
              @click.native.prevent="handleRow(scope.row, 3)"
              class="borbot"
              type="primary"
              plain
              size="small"
            >
              查询
            </el-button>
            <!-- 换电柜：隐藏更改参数、指令 -->
            <el-button
              @click.native.prevent="handleRow(scope.row, 4)"
              class="borbot"
              type="primary"
              plain
              size="small"
              v-if="equipType == 'CHARGING_CABINET'"
            >
              平台链接配置
            </el-button>
            <el-button
              @click.native.prevent="handleRow(scope.row, 5)"
              class="borbot"
              type="primary"
              plain
              size="small"
              v-if="equipType == 'CHARGING_CABINET'"
            >
              指令
            </el-button>
            <el-button
              @click.native.prevent="handleRow(scope.row, 8)"
              class="borbot"
              type="primary"
              plain
              size="small"
            >
              标签设置
            </el-button>
            <el-popconfirm
              title="确定要删除吗？"
              @onConfirm="handleRow(scope.row, 7)"
            >
              <el-button
                slot="reference"
                type="danger"
                plain
                size="small"
                class="borbot"
                >删除</el-button
              >
            </el-popconfirm>
            
            <el-button
              type="text"
              size="small"
              slot="reference"
              class="more_btn"
              >操作<i class="el-icon-d-arrow-right el-icon--right"></i
            ></el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :page="page"
      :limit="size"
      :total="total"
      @pagination="pagination"
    />
    <!-- 升级弹框 -->
    <el-dialog
      :title="diaTitle"
      :visible.sync="updateDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      center
    >
      <!-- @resetData="resetData" -->
      <Operate
        v-if="diaType == 1"
        ref="operate"
        :equipList="equipList"
        :updateDialogVisible="updateDialogVisible"
        :equipType="equipType"
        :updateType="updateType"
        :conditionForm="conditionForm"
        @closeDialog="closeDialog"
      ></Operate>
      <Log
        v-else-if="diaType == 2"
        :equipList="equipList"
        :updateDialogVisible="updateDialogVisible"
        @closeDialog="closeDialog"
      ></Log>
      <!-- 3 查询 -->
      <Param
        v-else-if="diaType == 4"
        :equipList="equipList"
        :updateDialogVisible="updateDialogVisible"
        @closeDialog="closeDialog"
      >
      </Param>
      <Cmd
        v-else-if="diaType == 5"
        :equipList="equipList"
        :updateDialogVisible="updateDialogVisible"
        @closeDialog="closeDialog"
      ></Cmd>
      <!-- 6 批量新增 -->
      <Codes
        v-else-if="diaType == 6"
        :updateDialogVisible="updateDialogVisible"
        :equipType="equipType"
        @closeDialog="closeDialog"
        @resetData="resetData"
      ></Codes>
      <AddUpdate
        v-else-if="diaType == 8"
        :equipType="equipType"
        :updateDialogVisible="updateDialogVisible"
        @closeDialog="closeDialog"
      ></AddUpdate>
    </el-dialog>

    <!-- 日志弹框 -->
    <el-dialog
      :title="
        logType == 1
          ? `连接日志（${rowData.code}）`
          : `告警日志（${rowData.code}）`
      "
      :visible.sync="logDialog"
      width="45%"
      @close="logDialogClose"
      :close-on-click-modal="false"
    >
      <el-table
        :data="logData"
        border
        style="width: 100%"
        v-loading="logLoading"
      >
        <el-table-column label="状态">
          <!-- 状态（1：发生，0：结束） -->
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'warning'">
              {{ statusFormat(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
      </el-table>
      <Pagination
        :page="logSearchForm.pageNum"
        :limit="logSearchForm.pageSize"
        :total="logTotal"
        @pagination="logPagination"
      />
    </el-dialog>

    <el-dialog
      :title="
        logType == 1
          ? `连接日志（${rowData.code}）`
          : `告警日志（${rowData.code}）`
      "
      :visible.sync="warnDialog"
      width="50%"
      @close="logDialogClose"
      :close-on-click-modal="false"
    >
      <el-table
        v-if="logType == 2"
        :data="warnData"
        border
        style="width: 100%"
        v-loading="logLoading"
      >
        <el-table-column prop="semaphoreName" label="信号量"></el-table-column>

        <el-table-column label="状态" width="70px">
          <!-- 状态（1：发生，0：结束） -->
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'warning'">
              {{ alarmFormat(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="occurrenceTime"
          label="发生时间"
          min-width="160px"
        ></el-table-column>
        <el-table-column
          prop="recoveryTime"
          label="消除时间"
          min-width="160px"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="160px"
        ></el-table-column>
      </el-table>
      <Pagination
        :page="logSearchForm.pageNum"
        :limit="logSearchForm.pageSize"
        :total="logTotal"
        @pagination="logPagination"
      />
    </el-dialog>

    <!-- 备注弹框 -->
    <el-dialog
      title="编辑备注信息"
      :visible.sync="remarkDialog"
      width="30%"
      @close="remarkClose"
      :close-on-click-modal="false"
    >
      <el-form :model="remarkForm" ref="remarkForm" label-width="60px">
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="remarkForm.remark"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetRemarkDialog">重 置</el-button>
        <el-button type="primary" @click="confirmRemark">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑设备标签 -->
    <Dialog
      :visible="visible"
      width="25%"
      class="tagDialog"
      :loading="dialogBtnLoading"
      title="编辑设备标签"
      @confirmDialog="submitDialogForm('dialogForm')"
      @cancelDialog="cancelDialog"
    >
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        label-width="50px"
        :rules="dialogRules"
      >
        <el-form-item label="标签" prop="tagsId">
          <el-checkbox-group v-model="dialogForm.tagsId">
            <el-checkbox
              class="tag-radio"
              :label="item.id"
              v-for="(item, index) in tagList"
              :key="index"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
          <el-button
            type="primary"
            size="mini"
            plain
            @click="
              tagVisible = true;
              tagForm.name;
            "
            class="add_tag_btn"
            icon="el-icon-plus"
          ></el-button>
        </el-form-item>
        <el-form
          v-show="tagVisible"
          class="tagForm"
          :inline="true"
          ref="tagForm"
          :model="tagForm"
          label-width="120px"
          :rules="tagRules"
          ><el-form-item prop="name">
            <el-input
              v-model="tagForm.name"
              placeholder="请输入标签名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            ><el-button type="primary" size="small" plain @click="isSubmitTag"
              >确定</el-button
            ><i class="el-icon-close" @click="tagVisible = false"></i
          ></el-form-item>
        </el-form>
      </el-form>
    </Dialog>

    <!-- 批量设置设备标签 -->
    <Dialog
      :visible="tagsVisible"
      width="26%"
      class="tagsDialog"
      :loading="tagsBtnLoading"
      title="批量设置标签"
      @confirmDialog="submitTagsForm('tagsForm')"
      @cancelDialog="cancelTagsDialog"
    >
      <el-form
        ref="tagsForm"
        :model="tagsForm"
        label-width="70px"
        :rules="tagsRules"
      >
        <el-form-item label="已选设备">
          <div class="tags-data">
            <span
              v-for="(item, index) in selectData"
              :key="index"
              class="tag-one"
            >
              <el-tag v-if="index < 4">{{ item.code }}</el-tag></span
            >
          </div>
          <div class="more" v-if="selectData.length > 4">
            ......等{{ selectData.length }}个设备
          </div>
        </el-form-item>
        <el-form-item label="标签" prop="tagsId">
          <el-checkbox-group v-model="tagsForm.tagsId">
            <el-checkbox
              class="tag-radio"
              :label="item.id"
              v-for="(item, index) in tagList"
              :key="index"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
          <el-button
            type="primary"
            size="mini"
            plain
            @click="
              tagVisible = true;
              tagForm.name = '';
            "
            class="add_tag_btn"
            icon="el-icon-plus"
          ></el-button>
        </el-form-item>
        <el-form
          v-show="tagVisible"
          class="tagForm"
          :inline="true"
          ref="tagForm"
          :model="tagForm"
          label-width="120px"
          :rules="tagRules"
          ><el-form-item prop="name">
            <el-input
              v-model="tagForm.name"
              placeholder="请输入标签名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            ><el-button type="primary" size="small" plain @click="isSubmitTag"
              >确定</el-button
            ><i class="el-icon-close" @click="tagVisible = false"></i
          ></el-form-item>
        </el-form>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import Operate from "./operate.vue";
import Log from "./log.vue";
import Param from "./param.vue";
import Cmd from "./cmd.vue";
import Codes from "./codes.vue";
import AddUpdate from "./addUpdate";
import { equip, readversion, equipUpdate } from "@/api/cabint";
import { datasync } from "@/api/system";

import Pagination from "@/components/Pagination";

import { mapGetters } from "vuex";
import { removeNullUndefined } from "@/utils/index.js";
import { handleConfirm } from "@/utils/messageBox";

import Dialog from "@/components/Dialog";

export default {
  props: {
    // 设备类型
    equipType: {
      type: String,
      default: "",
    },
  },
  components: {
    Operate: Operate,
    Pagination: Pagination,
    Log: Log,
    Param: Param,
    Cmd: Cmd,
    Codes: Codes,
    AddUpdate: AddUpdate,
    Dialog,
  },
  computed: {
    ...mapGetters(["enums"]),
  },
  data() {
    return {
      listLoading: false,
      updateDialogVisible: false, //升级弹框
      logDialogVisible: false, //日志
      diaType: null, //弹框type
      diaTitle: "", //弹框title
      tableData: [],
      selectData: [], //列表选中data
      page: 1,
      size: 10,
      total: 0, //总数据
      // 搜索条件
      searchForm: {
        codes: "", //设备code
        code: "",
        masterVersion: "", //主控版本
        binVersion: "", //仓控版本
        cabinetVersion: "", //柜控版本
        equipmentType: "", //设备类型
        isOnline: "", //是否在线
        tagIds: [], //标签
        operatorName: "", //运营商
        isContain: 0, //是否包含选中标签
      },
      equipList: [], //已选设备
      logDialog: false, //日志弹框
      warnDialog: false, //日志弹框
      logType: "",
      logData: [],
      warnData: [],
      logSearchForm: {
        pageNum: 1,
        pageSize: 10,
        equipmentCode: "",
      },
      logTotal: 0,
      logLoading: false,

      // 备注
      remarkDialog: false,
      remarkForm: {
        id: "",
        remark: "",
      },

      rowData: {}, //行数据
      updateType: "", //区分单个升级还是批量

      conditionForm: {}, //条件升级
      tagList: [], //标签列表
      visible: false,
      dialogBtnLoading: false,
      dialogForm: {
        codes: "",
        tagsId: [],
      },
      dialogRules: {
        tagsId: [{ required: true, message: "请选择标签", trigger: "change" }],
      },
      tagVisible: false,
      tagForm: {
        name: "",
      },
      tagRules: {
        name: [{ required: true, message: "请输入标签名称", trigger: "blur" }],
      },

      // 批量设置标签
      tagsVisible: false,
      tagsBtnLoading: false,
      tagsForm: {
        codes: "",
        tagsId: [],
      },
      tagsRules: {
        tagsId: [{ required: true, message: "请选择标签", trigger: "change" }],
      },
    };
  },
  watch: {},
  async created() {
    this.searchForm.equipmentType = this.equipType;
    this.getList();
    await this.$store.dispatch("loglevel/loglevel");
    this.getTagList();
  },
  methods: {
    centerStyle() {
      return "text-align:center";
    },
    formatter(row, column, cellValue, index) {
      const valueMap = new Map([
        [1, "在线"],
        [0, "离线"],
      ]);
      return valueMap.get(cellValue);
    },
    statusFormat(val) {
      return this.enums.EQUIPMENT_CONNECT_STATUS.find(
        (item) => item.code == val
      ).label;
    },
    alarmFormat(val) {
      return this.enums.ALARM_FLAG.find((item) => item.code == val).label;
    },
    // 列表 data
    async getList() {
      this.listLoading = true;
      let param = { ...this.searchForm };
      if (param.codes) {
        param.codes = param.codes.split("\n").filter((p) => p);
      }

      //这里使用的是Set的一个特性，集合中不会包含重复项。
      if (param.codes.length > 100) {
        this.$message.error("最多只能输入100个设备号！");
        return;
      }
      this.conditionForm = { ...removeNullUndefined(param) };
      let params = Object.assign(
        {
          pageNum: this.page,
          pageSize: this.size,
        },
        param
      );
      if (params.codes.length == 1) {
        params.code = params.codes[0];
        delete params.codes;
      }
      const res = await equip(
        "/list",
        "post",
        { ...removeNullUndefined(params) },
        1
      ).catch((err) => {});
      if (res) {
        this.listLoading = false;
        this.tableData = res.data;
        this.total = Number(res.total);
      } else {
        this.listLoading = false;
        this.tableData = [];
        this.total = 0;
      }
    },
    resetData() {
      this.page = 1;
      this.size = 10;
      this.total = 0;
      this.searchForm = {
        codes: "", //设备code
        code: "", //设备code
        masterVersion: "", //主控版本
        binVersion: "", //仓控版本
        cabinetVersion: "", //柜控版本
        equipmentType: this.equipType, //设备类型
        isOnline: "", //是否在线
        tagIds: [], //标签
        operatorName: "", //运营商
        isContain: 0,
      };
      this.getList();
    },
    // 分页
    pagination(val) {
      this.page = val.page;
      this.size = val.limit;
      this.getList();
    },
    // 搜索
    doSearch() {
      this.getList();
    },
    // 重置
    clearSearch() {
      this.searchForm = {
        codes: "", //设备code
        code: "", //设备code
        masterVersion: "", //主控版本
        binVersion: "", //仓控版本
        cabinetVersion: "", //柜控版本
        equipmentType: this.equipType, //设备类型
        isOnline: "", //是否在线
        tagIds: [], //标签
        operatorName: "", //运营商
        isContain: 0,
      };
      this.doSearch();
    },
    //限制输入特殊字符
    keyUp(e) {
      let str = e.target.value.replace(
        /[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
        ""
      );
      e.target.value = str;
      this.searchForm.codes = str;
    },
    // 只能输入汉字、英文、数字
    keyInput(e) {
      let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
      e.target.value = str;
      this.searchForm.codes = str;
    },
    logRow(row, type) {
      this.rowData = row;
      this.logType = type;
      this.logDialog = type == 1 ? true : false;
      this.warnDialog = type == 2 ? true : false;
      this.logSearchForm.equipmentCode = row.code;

      this.warnData = [];
      this.logData = [];
      this.getLogData();
    },
    async getLogData() {
      this.logLoading = true;
      let url = this.logType == 1 ? "/connect/list" : "/alarm/list";
      // 获取日志列表数据
      const datas = await equip(url, "post", this.logSearchForm).finally(
        () => (this.logLoading = false)
      );
      if (datas.code == 200) {
        this.logData = this.logType == 1 ? datas.data : [];
        this.warnData = this.logType == 2 ? datas.data : [];
        this.logTotal = +datas.total;
      }
    },
    logPagination(val) {
      this.logSearchForm.pageNum = val.page;
      this.logSearchForm.pageSize = val.limit;
      this.getLogData();
    },
    logDialogClose() {
      this.resetLogData();
    },
    resetLogData() {
      this.logType = "";
      this.logData = [];
      this.warnData = [];
      this.logSearchForm = {
        pageNum: 1,
        pageSize: 10,
        equipmentCode: "",
      };
      this.logTotal = 0;
    },
    handleRow(row, type) {
      this.diaType = type;
      this.equipList = [row];
      switch (type) {
        case 1:
          this.diaTitle = "升级";
          this.updateDialogVisible = true;
          this.updateType = "single"; //单个升级
          break;
        case 2:
          this.diaTitle = "新增日志提取";
          this.updateDialogVisible = true;
          break;
        case 3:
          this.$confirm("确认要查询吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.isSearch();
          });
          break;
        case 4:
          this.diaTitle = "平台链接配置 ";
          this.updateDialogVisible = true;
          break;
        case 5:
          this.diaTitle = "远程控制";
          this.updateDialogVisible = true;
          break;
        case 7:
          this.deleteRow(row);
          break;
        case 8:
          this.visible = true;
          this.getTagsIdByCode(row.code);
          break;
      }
    },
    // 根据equipCode查询标签
    async getTagsIdByCode(code) {
      const data = await datasync(
        "/query/tags",
        "post",
        {
          code: code,
        },
        1
      );
      this.dialogForm.tagsId =
        data.data && data.data.length > 0
          ? data.data.map((item) => {
              return item.tagsId;
            })
          : [];
    },
    // 删除
    deleteRow(row) {
      this.listLoading = true;
      equip(`/delete?id=${row.id}`, "delete", 1)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
            // 删除成功 更新列表
            this.resetData();
          }
        })
        .finally((complete) => {
          this.listLoading = false;
        });
    },
    // 批量查询
    batchSearch() {
      this.equipList = this.selectData;
      this.$confirm("确认要批量查询吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.isSearch();
      });
    },
    // 批量新增
    batchAdd() {
      this.updateDialogVisible = true;
      this.diaTitle = "批量新增";
      this.diaType = 6;
    },
    // 导入并升级
    batchAddUpdate() {
      this.updateDialogVisible = true;
      this.diaTitle = "导入并升级";
      this.diaType = 8;
    },
    // 条件升级
    conditionUpdate() {
      this.$confirm("确认要根据点击“搜索”按钮后的搜索条件进行升级吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.updateDialogVisible = true;
        this.diaTitle = "批量升级(条件)";
        this.diaType = 1;
        this.updateType = "condition";
      });
    },

    async isSearch() {
      const loading = this.$loading({
        lock: true,
        text: "操作中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
      });

      let codes = this.equipList.map((item) => {
        return item.code;
      });
      let codeparm =
        codes.length == 1 ? { code: codes.join() } : { codes: codes.join(",") };
      let url = codes.length == 1 ? "/read/version" : "/batchread/version";
      await readversion(url, codeparm)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
            // 查询成功 更新列表
            this.getList();
          }
        })
        .finally((err) => {
          loading.close();
        });
    },
    closeDialog() {
      this.updateDialogVisible = false;
    },
    handleSelectionChange(val) {
      this.selectData = val;
    },
    // 批量升级
    batchUpdate() {
      this.updateDialogVisible = true;
      this.equipList = this.selectData;
      this.diaTitle = "批量升级(选中)";
      this.diaType = 1;
      this.updateType = "batch";
    },
    isRemarkRow(row) {
      this.rowData = row;
      this.remarkDialog = true;
      const { id, remark } = row;
      this.remarkForm = { id, remark };
    },
    remarkClose() {
      this.remarkForm = {
        id: "",
        remark: "",
      };
    },
    resetRemarkDialog() {
      this.remarkForm.remark = "";
    },

    confirmRemark() {
      this.$confirm("确定要编辑当前备注信息吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.doEditRemark();
      });
    },
    doEditRemark() {
      equip("/update/remark", "put", this.remarkForm).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: res.message,
            type: "success",
          });
          this.remarkDialog = false;
          this.getList();
        }
      });
    },
    // 查询全部标签
    async getTagList() {
      const data = await datasync("/tags/all");
      this.tagList = data.data;
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          handleConfirm(`确定要编辑当前设备标签吗？`, "warning", "提示")
            .then((res) => {
              this.doAddTag();
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    cancelDialog() {
      this.visible = false;
      this.dialogForm = {
        codes: "",
        tagsId: [],
      };
      this.tagForm = {
        name: "",
      };
      this.dialogBtnLoading = false;
    },
    doAddTag() {
      this.dialogBtnLoading = true;
      datasync(
        "/energy/set/tags",
        "post",
        {
          code: this.equipList[0].code,
          tagIds: this.dialogForm.tagsId.join(","),
        },
        1
      )
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.cancelDialog();
            this.getList();
          }
        })
        .finally(() => (this.dialogBtnLoading = false));
    },
    isSubmitTag() {
      this.$refs["tagForm"].validate((valid) => {
        if (valid) {
          handleConfirm(`确定要新增标签吗？`, "warning", "提示")
            .then((res) => {
              datasync(
                "/tags/insert",
                "post",
                { name: this.tagForm.name },
                1
              ).then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.message);
                  this.tagVisible = false;
                  this.getTagList();
                }
              });
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },

    // 批量设置标签
    batchSetTags() {
      this.tagsVisible = true;
    },
    cancelTagsDialog() {
      this.tagsVisible = false;
      this.tagsForm = {
        codes: "",
        tagsId: [],
      };
      this.tagTabs = {
        name: "",
      };
      this.tagsBtnLoading = false;
    },
    submitTagsForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          handleConfirm(`确定要给所选设备设置标签吗？`, "warning", "提示")
            .then((res) => {
              this.batchAddTag();
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    batchAddTag() {
      this.tagsBtnLoading = true;
      datasync("/tags/savebatch", "post", {
        codes: this.selectData.map((item) => {
          return item.code;
        }),
        tagIds: this.tagsForm.tagsId,
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.cancelTagsDialog();
            this.selectData = [];
            // 刷新列表
            this.doSearch();
            this.$refs.multipleTable.clearSelection();
          }
        })
        .finally(() => (this.tagsBtnLoading = false));
    },
    tagCheckChange(e) {
      this.searchForm.isContain = e ? 1 : 0;
    },
  },
};
</script>
<style scoped lang="scss">
@import "@/assets/css/scss.scss";

.titles {
  @include flexLayout(center, space-between);
  margin-top: -20px;

  .btn_right {
    span {
      margin-right: 10px;
      font-size: 14px;
    }
  }
}

.search-form {
  @include flexLayout(flex-start, space-between);

  .search_ipts {
    width: 85%;
    @include flexLayout(flex-start, flex-start);
  }

  .el-form-item__content {
    width: 100%;
  }
  .el-form-item {
    margin-right: 3px;
  }
}
.isContain {
  margin-right: 10px;
  color: #f56c6c;
  border-color: #f56c6c;
  ::v-deep .el-checkbox__inner {
    border-color: #f56c6c;
  }
  ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
    border-color: #409eff;
  }
}
.borbot {
  margin-bottom: 8px;
}

.more_btn {
  color: #409eff;
}

.log_btn {
  color: #e6a23c;
  margin-right: 6px;
}

.el-popover {
  .el-button {
    display: block;
    margin-left: 0;
  }
}

::v-deep .text-col {
  .el-form-item__content {
    width: 85%;
  }
}

.word-wrap {
  white-space: pre-wrap;
}
// 解决element-ui的表格设置固定栏后，边框线消失的bug
::v-deep .el-table {
  th:not(.is-hidden):last-child {
    top: -1px;
  }
}
::v-deep .el-table td:last-child,
::v-deep .el-table th:last-child {
  border-left: 1px solid #ebeef5;
}

::v-deep .tagDialog,
::v-deep .tagsDialog {
  .el-dialog__body {
    min-height: 220px;
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
.tagsName {
  display: inline-block;
  @include exceedFlow(1);
}
.tagForm {
  margin-left: 70px;
  margin-top: 24px;
  .el-icon-close {
    margin-left: 20px;
    font-size: 24px;
    position: relative;
    top: 4px;
    color: #999;
  }
}
.tags-data {
  @include exceedFlow(4);
  .tag-one {
    margin-left: 5px;
  }
}
.more {
  margin-left: 6px;
}
.add_tag_btn {
  margin-left: 10px;
}
.filters {
  @include flexLayout(center, flex-start);
  flex-wrap: wrap;
  margin-bottom: 10px;
  .el-form-item {
    width: 20%;
    margin: 0;
    line-height: 32px;
  }
  .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
  .search-btns {
    margin-left: 30px;
  }
  .el-select {
    width: 100% !important;
  }
}
.tag-item {
  width: auto !important;
  ::v-deep .el-form-item__content {
    @include flexLayout(baseline, flex-start);
  }
}
</style>
